package de.koller.aframe.util.noise.n1D;

import de.koller.aframe.util.math.FunctionPreview;
import de.koller.aframe.util.math.IFunction;
import de.koller.aframe.util.math.interpolation.AInterpolation;
import java.util.Random;

public class Perlin1D implements IFunction {

	private final Random rnd;

	private final float[] data = new float[ 8 ];
	
	public Perlin1D( Random rnd ) {
		this.rnd = rnd;
		
		for( int i = 0; i < data.length; i++ )
			data[i] = rnd.nextFloat();
	}
	
	@Override
	public float getValue( float x ) {
		if( x > 1 || x <= 0 )
			return 0;
		
		int i = (int)(x * data.length);
		float seg = (1f / (float)data.length);
		float f = AInterpolation.interpolate( getValue(i-1), getValue(i), getValue(i+1), getValue(i+2), 
				(x - (seg*i)) / seg );
		return f;
	}
	
	private float getValue( int i ) {
		if( i < 0 )
			return data[0];
		if( i >= data.length )
			return data[ data.length-1 ];
		return data[i];
	}
	
	public static void main( String[] args ) {
		while( true ) {
			FunctionPreview.dontscale( -.125f );
			FunctionPreview.showFunction( -.75f, 1.75f, new Perlin1D( new Random() ) );
		}
	}
	
}
